package com.flashcash.solu.view.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.util.Pair;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flashcash.kotlin.activity.LoaningActivity;
import com.flashcash.kotlin.activity.PolicyActivity;
import com.flashcash.kotlin.data.BankBean;
import com.flashcash.kotlin.data.CouponBean;
import com.flashcash.kotlin.data.LoaningAmoutBean;
import com.flashcash.kotlin.data.PolicyType;
import com.flashcash.kotlin.data.UserBankInfo;
import com.flashcash.kotlin.data.WithdrawChannel;
import com.flashcash.kotlin.trace.TraceManager;
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.kotlin.utils.SpanBuilder;
import com.flashcash.kotlin.widget.DatePickerDialog;
import com.flashcash.kotlin.widget.LocalEditText;
import com.flashcash.solu.R;
import com.flashcash.solu.bean.ApplyLoanInfo;
import com.flashcash.solu.bean.ApplySkypayLoanInfo;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.FieldParamsInt;
import com.flashcash.solu.common.adapter.WithdrawChannelAdapter;
import com.flashcash.solu.harvester.collectin.Collector;
import com.flashcash.solu.harvester.collectin.PermissionUtil;
import com.flashcash.solu.utils.StringFormatUtils;
import com.flashcash.solu.view.SubmittedLoanActivity;
import com.flashcash.solu.view.camera.FaceDetectorFragment;
import com.flashcash.solu.view.fragment.presenter.LoaningFraPreImp;
import com.flashcash.solu.view.fragment.presenter.LoaningFraPresenter;
import com.flashcash.solu.widget.XLeoSp;
import com.flashcash.solu.widget.selfdefdialog.DialogManager;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.hwangjr.rxbus.RxBus;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.x.leo.apphelper.data.cache.CacheDataManage;
import com.x.leo.apphelper.log.XLog;
import com.x.leo.apphelper.utils.ErrorHandler;
import com.x.leo.apphelper.utils.ErrorHandlerInterface;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import rx.Subscriber;

import static android.app.Activity.RESULT_OK;


/**
 * Created by milo on 17-2-14.
 */

public class LoaningFragment extends FaceDetectorFragment<LoaningFraPresenter> implements
        LoaningFraView {

    public static final String KEY_AGREE = "agree";
    public static final String KEY_LOAN_APP_ID = "loan_app_id";

    public static final int REQUEST_CODE = 212;

    private static final int REQUEST_COUPON_CHOOSE = 1532;
    private static final int BANK_INFO_SELECT = 1888;
    private static final int FACE_DETECT_REQUEST_CODE = 0x010F;

    @BindView(R.id.id_textview_repayment_amount)
    TextView idTextviewRepaymentAmount;

    @BindView(R.id.id_textview_receiving_bank)
    TextView idTextviewReceivingBank;

    @BindView(R.id.id_textview_withdraw_channel)
    TextView idTextviewWithdrawChannel;

    @BindView(R.id.id_imagebutton_bank)
    ImageButton idImagebuttonBank;

    @BindView(R.id.id_edittext_bank_number)
    LocalEditText idEdittextBankNumber;

    /*@BindView(R.id.id_edittext_confirm_bank_number)
    LocalEditText idEdittextConfirmBankNumber;*/

    @BindView(R.id.id_edittext_bank_account_name)
    LocalEditText idEdittextBankAccountName;

    @BindView(R.id.id_textview_bank_card_expire_date)
    TextView idTextviewBankCardExpireDate;

    @BindView(R.id.id_edittext_email)
    LocalEditText idEdittextEmail;

    @BindView(R.id.id_edittext_use_loan)
    LocalEditText idEdittextUseLoan;

    @BindView(R.id.id_button_current_loan_ing)
    Button idButtonCurrentLoanIing;

    @BindView(R.id.id_textview_loan_selected_amount)
    TextView idTextviewLoanSelectedAmount;

    @BindView(R.id.id_textview_loan_selected_day)
    TextView idTextviewLoanSelectedDay;

    @BindView(R.id.id_linearlayout_receiving_bank)
    LinearLayout idLinearlayoutReceivingBank;

    @BindView(R.id.id_linearlayout_withdraw_channel)
    LinearLayout idLinearlayoutWithdrawChannel;

    @BindView(R.id.id_textview_coupon_select)
    TextView idTextviewCouponSelect;

    @BindView(R.id.id_textview_bank_name)
    TextView idTextviewBankName;

    @BindView(R.id.id_linearlayout_coupon_select)
    LinearLayout idLinearlayoutCouponSelect;

    @BindView(R.id.id_linearlayout_bank_name)
    LinearLayout idLinearlayoutBankName;

    @BindView(R.id.cb_aggreed)
    CheckBox CbAgreed;

    @BindView(R.id.tv_aggrement)
    TextView tv_aggrement;

    @BindView(R.id.id_imagebutton_back)
    ImageButton back;

    Dialog dialogPlus;
    static ApplyLoanInfo applyLoanInfo;
    static ApplySkypayLoanInfo applySkypayLoanInfo;
    private long mCouponId;
    private List<BankBean> mBankList;
    private List<WithdrawChannel> mWithdrawChannelList;


    private String cardMonth;
    private String cardYear;

    private Boolean isInputBankCardNumberDialogHasBeanShown = false;
    private boolean idEdittextBankNumberVisivble = false;

    private String bankNo = "";
    private String bankProvince = "";
    private String bankCity = "";

    private String curType = "";

    private LatestLoanAppBean totalAmount;
    private String withDrawChannelCode;
    private String accountNumber = "";//保存账户号码

    @Override
    protected LoaningFraPresenter initPresenter() {
        return new LoaningFraPreImp();
    }

    @Override
    protected boolean doPreBuildHeader() {
        return false;
    }


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_main_loaning;
    }

    @Override
    protected void initView(View view, Bundle savedInstanceState) {

        RxBus.get().register(this);
        /*idLinearlayoutCouponSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(LoaningFragment.this.getContext(),
                        ChooseCouponActivity.class), REQUEST_COUPON_CHOOSE);
            }
        });*/
        initLegalStatement();
        CbAgreed.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                CbAgreed.setSelected(isChecked);
            }
        });

        /*idButtonCurrentLoanIing.setOnTouchListener((v, event) -> {
            if (!v.isClickable()) {
                String ret = checkUnFillContent();
                if (!TextUtils.isEmpty(ret)) {
                    XLeoToast.makeText(getContext(), ret, Toast.LENGTH_SHORT).show();
                }
            }
            return false;
        });*/
        idButtonCurrentLoanIing.setOnClickListener(v -> {
            if (isCheckedField()) {
                applyLoanAppSubmit();
                /*if (!idEdittextBankNumberVisivble) {
                    if (isLawAgreed()) {//已同意贷款
                        submitLoan();
                    }
                } else {
                    if (isCheckeBankNum()) {
                        if (isLawAgreed()) {//已同意贷款
                            submitLoan();
                        }
                    }
                }*/
            }
        });
//        StoreUtils.saveAll(getBaseActivity());
    }

    /*public String checkUnFillContent() {
//        if (TextUtils.isEmpty(idTextviewReceivingBank.getText())) {
//            return getString(R.string.enter_receive_bank);
//        }
        if (TextUtils.isEmpty(idTextviewWithdrawChannel.getText())) {
            return getString(R.string.enter_withdraw_channel);
        }
        if (TextUtils.isEmpty(idEdittextBankNumber.getText())) {
            Editable bankNumber = idEdittextBankNumber.getText();
            if (bankNumber != null && bankNumber.length() > 64) {
                return getString(R.string.bank_card_no_too_long);
            }
            return getString(R.string.enter_bank_no);
        }
        Editable reason = idEdittextUseLoan.getText();
        if (reason != null && reason.length() > 128) {
            return getString(R.string.loan_reason_too_long);
        }
        return null;
    }*/

    @Override
    public void onDetach() {
        super.onDetach();
    }

    private void initLegalStatement() {
//        String statement = getString(R.string.textview_video_statement);
        String statement = "I have read and accepted the 《Loan Guarantee Agreement》";
        String agree = "《Loan Guarantee Agreement》";
//        String agree = getString(R.string.text_loan_agreement_title);
        int start = statement.indexOf(agree);
        Function0<Unit> func = new Function0<Unit>() {
            @Override
            public Unit invoke() {
                showLegalAgreement();
                return null;
            }
        };
        SpannableStringBuilder result = new SpanBuilder().init(statement)
                .setLinkSpan(start, start + agree.length(), getResources().getColor(R.color
                        .theme_blue), func)
                .result();
        tv_aggrement.setText(result);
        tv_aggrement.setMovementMethod(new LinkMovementMethod());
    }

    //点击这里，跳转贷款协议
    private void showLegalAgreement() {
        /*if (getArguments() != null) {
            LatestLoanAppBean latestLoanAppBean = getArguments().getParcelable(FieldParams
                    .LOANING_LOAN_DATA);
            if (latestLoanAppBean != null) {
                DialogManager.showHtmlDialog(getContext(), BuildConfig.CONTRACT_URL +
                        "?loanId=" + latestLoanAppBean.getLoanAppId(), getString
                        (R.string.title_loan_agreement_title), true);
            }
        }*/
        if (totalAmount != null) {
            gotoLawAgreed();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_COUPON_CHOOSE && resultCode == RESULT_OK) {//优惠券，不用管
            CouponBean couponBean = CacheDataManage.INSTANCE.obtainData(FieldParamsInt
                    .COUPON_CHOOSED_NAME, CouponBean.class);
            if (couponBean != null) {
                double toReduce = couponBean.getDischargeInterestDay() * XLeoSp.getInstance
                        (getContext()).getDouble(FieldParams.CURRENT_LOAN_RATE, 0.01);
                idTextviewCouponSelect.setText(couponBean.getTitle() + " " + "-" + toReduce);
                mCouponId = couponBean.getId();
                Bundle arguments = getArguments();
                if (arguments != null) {
                    LatestLoanAppBean latestLoanAppBean = (LatestLoanAppBean) arguments.get
                            (FieldParams.LOANING_LOAN_DATA);
                    if (latestLoanAppBean != null && latestLoanAppBean.getTotalAmount() > 0.0) {
                        idTextviewRepaymentAmount.setText("PHP " + StringFormatUtils
                                .moneyFormatWithSplitWithUnitWithoutDecimal(latestLoanAppBean.getTotalAmount
                                        () * (1 - toReduce), getContext()));
                    } else {
                        XLeoToast.showMessage(R.string.error_occured);
                        return;
                    }
                } else {
                    XLeoToast.showMessage(R.string.error_occured);
                    return;
                }
            } else {
                idTextviewCouponSelect.setText("");
                mCouponId = -1;
            }
        } else if (requestCode == BANK_INFO_SELECT && resultCode == RESULT_OK) {
            bankNo = data.getStringExtra("bankNo");
            bankProvince = data.getStringExtra("bankProvince");
            bankCity = data.getStringExtra("bankCity");
            String bankName = data.getStringExtra("bankName");
            idTextviewBankName.setText(bankName);
            idLinearlayoutBankName.setVisibility(View.VISIBLE);
        } else if (requestCode == REQUEST_CODE && resultCode == PolicyActivity.RESULT_CODE) {//同意完协议，请求活体检测
//            Toast.makeText(getContext(), totalAmount.getProductId() + "", Toast.LENGTH_SHORT).show();
//            showFaceDetectorDialog();
        }
        /*else if (requestCode == FACE_DETECT_REQUEST_CODE) {//活体检测结果
            if (resultCode == Activity.RESULT_OK) {//检测成功，上传数据
                showLoading();
//                XLeoToast.showMessage("准备上传数据");
                Toast.makeText(getContext(), "准备上传数据", Toast.LENGTH_SHORT).show();
                submitButtonStateUpdate(false);
                mPresenter.uploadFaces(new DeltaHolder().getDelta()); // 上传大礼包
            } else {//检测出错
                if (data == null) {
                    XLeoToast.showMessage(R.string.detect_live_face_fail);
                } else if (data.getExtras() != null) {
                    XLeoToast.showMessage(data.getExtras().getString(FieldParams.LivenessExtras.FAILED_MSG));
                }
                XLeoToast.showMessage(R.string.detect_live_face_fail);
            }
        }*/
    }

    /*@Subscribe
    public void onSubmitLoan(EventCollection.SubmitLoan event) {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event
                .BTN_BANK_INFO_SUBMIT, null);
        //提交贷款
        if (applySkypayLoanInfo != null) {
//            mPresenter.applySkypayLoan(applySkypayLoanInfo);//并在提交成功后跳转到提交成功页面
            XLeoToast.showMessage("准备提交贷款");
        }
    }*/

    @Override
    protected void initData() {
        mPresenter.requestLoanInfo();
        back.setOnClickListener(v -> {
            getActivity().finish();
        });
    }

    public boolean isCheckeBankNum() {
        if (TextUtils.isEmpty(idEdittextBankNumber.getText().toString())) {
            Toast.makeText(getContext(), getString(R.string.enter_bank_no), Toast.LENGTH_SHORT).show();
            return false;
        } else if ("GCash(preferred)".equals(curType) || "Coins".equals(curType)) {
            if (!idEdittextBankNumber.getText().toString().startsWith("09") && !idEdittextBankNumber.getText().toString().startsWith("08")) {
                XLeoToast.showMessage(getString(R.string.show_input_bank_number_start_with));
                return false;
            } else if (idEdittextBankNumber.getText().toString().length() != 11) {
                XLeoToast.showMessage("The account number is a 11-digits phone number starting with 08 or 09");
                return false;
            }
        }
        return true;
    }

    public boolean isCheckedField() {
        if (TextUtils.isEmpty(idTextviewWithdrawChannel.getText().toString())) {
//            XLeoToast.showMessage(getString(R.string.show_confirm_input_withdraw_channel));
            Toast.makeText(getContext(), getString(R.string.show_confirm_input_withdraw_channel), Toast.LENGTH_SHORT).show();
            return false;
        }

        if (idEdittextBankNumber.getVisibility() == View.VISIBLE) {
            if (TextUtils.isEmpty(idEdittextBankNumber.getText().toString())) {
//                XLeoToast.showMessage(getString(R.string.enter_bank_no));
                Toast.makeText(getContext(), getString(R.string.enter_bank_no), Toast.LENGTH_SHORT).show();
                return false;
            } else if (idEdittextBankNumber.getText().toString().length() > 64) {
                Toast.makeText(getContext(), getString(R.string.bank_card_no_too_long), Toast.LENGTH_SHORT).show();
                return false;
            }
        }

//        if (!idEdittextBankNumber.checkLegal()) {
//            XLeoToast.showMessage(getString(R.string.show_input_bank_number));
//            return false;
//        }
        /*if (!idEdittextConfirmBankNumber.checkLegal()) {
            XLeoToast.showMessage(getString(R.string.show_confirm_input_bank_number));
            return false;
        }
        if (!idEdittextConfirmBankNumber.getText().toString().equals(idEdittextBankNumber.getText
        ().toString())) {
            XLeoToast.showMessage(getString(R.string.show_bank_number_inconsistent));
            return false;
        }*/
//        if (TextUtils.isEmpty(idEdittextBankAccountName.getText().toString())) {
//            XLeoToast.showMessage(getString(R.string.show_input_bank_account_name));
//            return false;
//        }
//        if (TextUtils.isEmpty(idTextviewBankCardExpireDate.getText().toString())) {
//            XLeoToast.showMessage(getString(R.string.show_input_bank_card_expiry_date));
//            return false;
//        }
//        if (!idEdittextEmail.checkLegal()) {
//            XLeoToast.showMessage(getString(R.string.show_input_email));
//            return false;
//        }
//        if (!idEdittextUseLoan.checkLegal()) {
//            XLeoToast.showMessage(getString(R.string.show_input_loan_usage));
//            return false;
//        }
        return true;
    }

    @OnClick(R.id.id_linearlayout_receiving_bank)
    public void setReceivingBank() {
        if (mBankList != null) {
            onBankRequestSuccess("BANK_CHOOSE", mBankList);
        } else {
            mPresenter.requestBankList("BANK_CHOOSE");
        }
    }

    @OnClick(R.id.id_linearlayout_withdraw_channel)
    public void setWithdrawChannel() {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_WITHDRAWAL_OPTION, null);
        if (mWithdrawChannelList != null) {
            onWithdrawChannelRequestSuccess(mWithdrawChannelList);
        } else {
            mPresenter.requestWithdrawChannels();
        }
    }

    @OnClick(R.id.id_linearlayout_bank_card_expire_date)
    public void bankCardExpireDateClick() {
        new DatePickerDialog(mActivity, getString(R.string.please_choose_date), DatePickerDialog
                .DatePickerMode.MODE_YM, (year, month) -> {
            cardMonth = month;
            cardYear = year.substring(year.length() - 2, year.length());
            idTextviewBankCardExpireDate.setText(String.format("%s/%s", cardMonth, cardYear));
        }).show();
    }

    /*@OnClick(R.id.id_edittext_bank_number)
    public void bankCardNumberClick() {
        if (!isInputBankCardNumberDialogHasBeanShown) {
            Dialog dialog = new Dialog(mActivity);
            View view = LayoutInflater.from(mActivity).inflate(R.layout
                    .dialog_input_bank_card_number_tips, null, false);

            view.findViewById(R.id.button_confirm).setOnClickListener(v -> dialog.dismiss());
            dialog.setContentView(view);
            dialog.setCancelable(true);
            dialog.show();
            isInputBankCardNumberDialogHasBeanShown = true;
        }
    }*/

    @Override
    public void resetButton() {
//        idButtonCurrentLoanIing.setClickable(true);
    }

    @Override
    public void onApplyLoanSuccess() {
        getBaseActivity().dismissLoading();
        RxBus.get().post(new EventCollection.LoanSuccess());
        if (mActivity instanceof LoaningActivity) {
            mActivity.finish();
        }
//        idEdittextBankNumber.setEnabled(false);
//        idEdittextUseLoan.setEnabled(false);
//        idLinearlayoutCouponSelect.setClickable(false);
//        idLinearlayoutReceivingBank.setClickable(false);
//        idButtonCurrentLoanIing.setClickable(true);
//        idButtonCurrentLoanIing.setClickable(true);
//        idButtonCurrentLoanIing.setText(R.string.goto_record_video);
//        idButtonCurrentLoanIing.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                onApplyLoanSuccess();
//            }
//        });
//        showFaceDetectorDialog();
    }

    @Override
    public void onAmountObtain(Pair<Pair<LatestLoanAppBean, LoaningAmoutBean>, UserBankInfo> it) {
        if (getArguments() == null) {
            setArguments(new Bundle());
        }
        Bundle arguments = getArguments();
        if (arguments != null) {
            arguments.putParcelable(FieldParams.LOANING_LOAN_DATA, it.first.first);
            totalAmount = it.first.first;
            arguments.putSerializable(FieldParams.LOANING_CURRENT_DETAIL, it.first.second);
            arguments.putSerializable(FieldParams.USER_BANK_INFO, it.second);
        }
        injectViews();
    }

    private void injectViews() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            LoaningAmoutBean loaningAmoutBean = (LoaningAmoutBean) arguments.getSerializable
                    (FieldParams.LOANING_CURRENT_DETAIL);
            if (getView() == null || loaningAmoutBean == null || loaningAmoutBean.getDueAmount()
                    == null || loaningAmoutBean.getInterest() == null || loaningAmoutBean
                    .getIssueAmount() == null || loaningAmoutBean.getServiceFee() == null ||
                    loaningAmoutBean.getTotalAmount() == null) {
                XLeoToast.showMessage(R.string.error_occured);
                return;
            }
            //((TextView) getView().findViewById(R.id.tv_due_amount)).setText(String.format
            // (getString(R.string.total_amount), StringFormatUtils
            // .moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean.getTotalAmount(), getContext())));
//            ((TextView) getView().findViewById(R.id.tv_interest)).setText(String.format(getString
//                    (R.string.interest), StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal
//                    (loaningAmoutBean.getInterest(), getContext())));
            ((TextView) getView().findViewById(R.id.tv_issue_amount)).setText("PHP " + StringFormatUtils
                    .moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean.getIssueAmount(),
                            getContext()));
//            ((TextView) getView().findViewById(R.id.tv_service_fee)).setText(String.format
//                    (getString(R.string.service_fee_amout), StringFormatUtils
//                            .moneyFormatWithSplitWithUnitWithoutDecimal(loaningAmoutBean.getServiceFee(),
//                                    getContext())));
            LatestLoanAppBean totalAmount = arguments.getParcelable(FieldParams.LOANING_LOAN_DATA);
            if (totalAmount == null) {
                XLeoToast.showMessage(R.string.error_occured);
                return;
            }
            idTextviewLoanSelectedAmount.setText("PHP " + StringFormatUtils
                    .moneyFormatWithSplitWithUnitWithoutDecimal(totalAmount.getAmount(), getContext()));
            idTextviewLoanSelectedDay.setText(StringFormatUtils.periodFormat(getContext(),
                    totalAmount.getPeriod(), totalAmount.getPeriodUnit()));
            idTextviewRepaymentAmount.setText("PHP " + StringFormatUtils.moneyFormatWithSplitWithUnitWithoutDecimal
                    (loaningAmoutBean.getDueAmount(), getContext()));

            UserBankInfo bankInfo = (UserBankInfo) arguments.getSerializable(FieldParams
                    .USER_BANK_INFO);
            if (bankInfo != null) {
                arguments.putString(FieldParams.BANK_CODE, bankInfo.getBankCode());
//                idEdittextBankNumber.setText(bankInfo.getCardNo());
                /*idEdittextConfirmBankNumber.setText(bankInfo.getCardNo());*/
                decodeCodeToName(bankInfo.getBankCode());

                idEdittextBankAccountName.setText(bankInfo.getFullName());
                cardMonth = bankInfo.getCardMonth();
                cardYear = bankInfo.getCardYear();
                if (!TextUtils.isEmpty(cardMonth) && !TextUtils.isEmpty(cardYear)) {
                    idTextviewBankCardExpireDate.setText(String.format("%s/%s", cardMonth, cardYear));
                }
            }
        }
    }

    private void decodeCodeToName(String bankCode) {
        if (bankCode == null) {
            return;
        }
        if (mBankList == null) {
            mPresenter.requestBankList("DECODE_CODE");
        } else {
            onBankRequestSuccess("DECODE_CODE", mBankList);
        }

    }

    @Override
    public void addBankError(Throwable throwable) {
        if (getContext() != null) {
            refreshUIState();
            ErrorHandlerInterface handler = new ErrorHandler.Builder()
                    .setMessage(throwable == null ? null : throwable.getMessage())
                    .setType(ErrorHandler.HandleType.DIALOG)
                    .setContext(getContext())
                    .createHandler();
            if (handler != null) {
                handler.show();
            }
        }
    }

    @Override
    public void addBankSuccess() {
        mActivity.dismissLoading();
        RxBus.get().post(new EventCollection.LoanSuccess());
        if (mActivity instanceof LoaningActivity) {
            //跳转到提交成功页面
            startActivity(new Intent(getContext(), SubmittedLoanActivity.class));
            mActivity.finish();
        }
    }

    @Override
    public void onBankRequestError(Throwable e) {
        if (getContext() != null) {
            ErrorHandlerInterface handler = new ErrorHandler.Builder()
                    .setContext(getContext())
                    .setMessage(e.getMessage())
                    .setType(ErrorHandler.HandleType.DIALOG)
                    .createHandler();
            if (handler != null) {
                handler.show();
            }
        }
    }

    @Override
    public void onBankRequestSuccess(String type, List<BankBean> bankBeans) {
        /*mBankList = bankBeans;
        if (TextUtils.equals(type, "BANK_CHOOSE")) {
            dialogPlus = DialogManager.newListViewDialog(getActivity())
//                .setContentHolder(new ListHolder())
                    .setGravity(Gravity.CENTER)
                    .setExpanded(false)
                    .setAdapter(new BankListAdapter(bankBeans, getContext(), new BankListAdapter
                            .OnBankItemClickListener() {
                        @Override
                        public void onItemClick(BankBean data) {
                            if (dialogPlus != null && dialogPlus.isShowing()) {
                                dialogPlus.dismiss();
                            }
                            idTextviewReceivingBank.setText(data.getBankName());
                            if (getArguments() == null) {
                                setArguments(new Bundle());
                            }
                            Bundle arguments = getArguments();
                            if (arguments != null) {
                                arguments.putString(FieldParams.BANK_CODE, data.getBankCode());
                            }
                        }
                    }))
                    .create();
            dialogPlus.show();
        } else if (TextUtils.equals(type, "DECODE_CODE")) {
            Bundle arguments = getArguments();
            if (arguments != null) {
                String bankCode = arguments.getString(FieldParams.BANK_CODE);
                if (!TextUtils.isEmpty(bankCode) && mBankList != null) {
                    for (BankBean bankBean : mBankList) {
                        if (TextUtils.equals(bankBean.getBankCode(), bankCode)) {
                            idTextviewReceivingBank.setText(bankBean.getBankName());
                            break;
                        }
                    }
                }
            }
        }*/

    }

    @Override
    public void onAmountObtainError(Throwable throwable) {
        XLog.INSTANCE.e("amount obtain error:", throwable, 100);
        if (isAdded()) {
            mActivity.finish();
        }
    }

    @Override
    public void onWithdrawChannelRequestSuccess(List<WithdrawChannel> withdrawChannels) {
        dialogPlus = DialogManager.newListViewDialog(getActivity())
//                .setContentHolder(new ListHolder())
                .setGravity(Gravity.CENTER)
                .setExpanded(false)
                .setAdapter(new WithdrawChannelAdapter(withdrawChannels, getContext(), data -> {
                    curType = data.getName();
                    /*if ("Bank".equals(curType)) {
                        Intent intent = new Intent(getContext(), BankInfoSelectActivity.class);
                        startActivityForResult(intent, BANK_INFO_SELECT);
                    }*/

                    if (idEdittextBankNumber.getVisibility() == View.VISIBLE && !TextUtils.isEmpty(idEdittextBankNumber.getText())) {//本来显示的并不为空，则保存值
                        accountNumber = idEdittextBankNumber.getText().toString();
                    }

                    if ("GCash(preferred)".equals(curType) || "Coins".equals(curType)
                            || "Paymaya".equals(curType)) {
                        idEdittextBankNumber.setVisibility(View.VISIBLE);
                        if (accountNumber != null && accountNumber.length() > 1) {
                            idEdittextBankNumber.setText(accountNumber);
                            idEdittextBankNumber.setSelection(accountNumber.length());
                        }
                        idEdittextBankNumberVisivble = true;
                        idTextviewBankName.setText("");
                        idLinearlayoutBankName.setVisibility(View.GONE);
                        if (curType.contains("GCash")) {
                            FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.SELECT_WITHDRAWAL_GCASH, null);
                        } else if (curType.contains("Coins")) {
                            FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.SELECT_WITHDRAWAL_COINS, null);
                        }
                    } else if ("Bank".equals(curType)) {
                        idEdittextBankNumber.setVisibility(View.VISIBLE);
                        if (accountNumber != null && accountNumber.length() > 1) {
                            idEdittextBankNumber.setText(accountNumber);
                            idEdittextBankNumber.setSelection(accountNumber.length());
                        }
                        idEdittextBankNumberVisivble = true;
                    } else {
                        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.SELECT_WITHDRAWAL_M_L_HULLIER, null);
                        idEdittextBankNumber.setVisibility(View.GONE);
                        idEdittextBankNumberVisivble = false;
                        idTextviewBankName.setText("");
                        idLinearlayoutBankName.setVisibility(View.GONE);
                    }
                    if (dialogPlus != null && dialogPlus.isShowing()) {
                        dialogPlus.dismiss();
                    }
                    idTextviewWithdrawChannel.setText(curType);
                    withDrawChannelCode = data.getCode();
                    if (getArguments() == null) {
                        setArguments(new Bundle());
                    }
                    Bundle arguments = getArguments();
                    if (arguments != null) {
                        arguments.putString(FieldParams.WITHDRAW_CHANNEL, data.getCode());
                    }
                }))
                .create();
        dialogPlus.show();
    }

    @Override
    public void onWithdrawChnanleRequestError(Throwable e) {
        if (getContext() != null) {
            ErrorHandlerInterface handler = new ErrorHandler.Builder()
                    .setContext(getContext())
                    .setMessage(e.getMessage())
                    .setType(ErrorHandler.HandleType.DIALOG)
                    .createHandler();
            if (handler != null) {
                handler.show();
            }
        }
    }

    @Override
    public void setWithdrawChannels(List<WithdrawChannel> withdrawChannels) {
        mWithdrawChannelList = withdrawChannels;
    }


    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshUIState();
        }
    }

    private void refreshUIState() {
        Bundle arguments = getArguments();
        if (arguments != null) {
            LatestLoanAppBean totalAmount = arguments.getParcelable(FieldParams.LOANING_LOAN_DATA);
            if (totalAmount == null) {
                XLeoToast.showMessage(R.string.error_occured);
                if (mActivity != null && mActivity instanceof LoaningActivity && mActivity
                        .isActive()) {
                    mActivity.finish();
                }
                return;
            }
            idButtonCurrentLoanIing.setClickable(true);
            idEdittextBankNumber.setEnabled(true);
            /*idEdittextConfirmBankNumber.setEnabled(true);*/
            idEdittextUseLoan.setEnabled(true);
            idLinearlayoutReceivingBank.setClickable(true);
            idLinearlayoutWithdrawChannel.setClickable(true);
            idLinearlayoutCouponSelect.setClickable(true);
            idButtonCurrentLoanIing.setClickable(true);
            idButtonCurrentLoanIing.setText(R.string.button_current_loan);
            /*idButtonCurrentLoanIing.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    applyLoanAppSubmit();
                }
            });*/
        }
    }

    //    @OnClick(R.id.id_button_current_loan_ing)
    public void applyLoanAppSubmit() {
//        Bundle arguments = getArguments();
        if (totalAmount != null) {
//            LatestLoanAppBean totalAmount = arguments.getParcelable(FieldParams.LOANING_LOAN_DATA);
//            XLeoToast.showMessage("before");
//            if (totalAmount == null) {
//                return;
//            }
            requestPermissions(0);//检测权限
            /*XLeoToast.showMessage("middle");
            Toast.makeText(getContext(), "mmm", Toast.LENGTH_LONG).show();
            CacheDataManage.INSTANCE.addData(TOTAL_AMOUNT, totalAmount);
            CacheDataManage.INSTANCE.addData(WITHDRAW_CHANNEL, withDrawChannelCode);

            TraceManager.INSTANCE.qualifyPermissions(mActivity, new Runnable() {
                @Override
                public void run() {

//                    Bundle arguments = getArguments();
                    LatestLoanAppBean totalAmount1 = CacheDataManage.INSTANCE.obtainData(TOTAL_AMOUNT, LatestLoanAppBean.class);
                    String withDrawChannelCode1 = CacheDataManage.INSTANCE.obtainData(WITHDRAW_CHANNEL, String.class);

                    if (totalAmount1 == null || TextUtils.isEmpty(withDrawChannelCode1)) {
                        XLog.INSTANCE.i(10, "loaning submit bank info error::argument: %s," +
                                        "totalAmout: %s"
                                , Boolean.toString(TextUtils.isEmpty(withDrawChannelCode1))
                                , Boolean.toString(totalAmount1 == null));
                        XLeoToast.showMessage(R.string.error_occured);
                        Toast.makeText(getContext(), "nnnn", Toast.LENGTH_LONG).show();
                        return;
                    }

                    new AlertDialog.Builder(getContext())
                            .setTitle(R.string.tips_title)
                            .setMessage(R.string.msg_check_withdraw_channel)
                            .setPositiveButton(R.string.button_ok, (dialog, which) -> {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
//                                    if (isCheckedField() && isLawAgreed()) {
                                if (!idEdittextBankNumberVisivble) {
                                    applySkypayLoanInfo = new ApplySkypayLoanInfo();
                                    applySkypayLoanInfo.setLoanAppId(totalAmount1.getLoanAppId());
//                                        applySkypayLoanInfo.setWithDrawChannel(arguments.getString(FieldParams.WITHDRAW_CHANNEL));
                                    applySkypayLoanInfo.setWithDrawChannel(withDrawChannelCode1);
                                    applySkypayLoanInfo.setAccountNo("");
                                    applySkypayLoanInfo.setBankNo("");
                                    applySkypayLoanInfo.setBankProvince("");
                                    applySkypayLoanInfo.setBankCity("");
//                                        idButtonCurrentLoanIing.setClickable(false);
                                    gotoLawAgreed();
                                } else {
                                    if (isCheckeBankNum()) {
                                        applySkypayLoanInfo = new ApplySkypayLoanInfo();
                                        applySkypayLoanInfo.setLoanAppId(totalAmount1.getLoanAppId());
//                                            applySkypayLoanInfo.setWithDrawChannel(arguments.getString(FieldParams.WITHDRAW_CHANNEL));
                                        applySkypayLoanInfo.setWithDrawChannel(withDrawChannelCode1);
                                        applySkypayLoanInfo.setAccountNo(idEdittextBankNumber.getText().toString());
                                        applySkypayLoanInfo.setBankNo(bankNo);
                                        applySkypayLoanInfo.setBankProvince(bankProvince);
                                        applySkypayLoanInfo.setBankCity(bankCity);
//                                            idButtonCurrentLoanIing.setClickable(false);
                                        gotoLawAgreed();
                                    }
                                }


//                                    }
                            })
                            .setNegativeButton(R.string.text_cancel, (dialog, which) -> {
                                if (dialog != null) {
                                    dialog.dismiss();
                                }
                            })
                            .show();
                }
            });*/
        }
    }

    public static final String[] neededPermissions = {
            Manifest.permission.READ_CONTACTS,
            Manifest.permission.ACCESS_COARSE_LOCATION,//粗精度定位
            Manifest.permission.ACCESS_FINE_LOCATION,//卫星定位
            Manifest.permission.READ_PHONE_STATE

    };

    /**
     * 检查权限
     *
     * @param permissionIndex
     */
    private void requestPermissions(int permissionIndex) {
        if (permissionIndex >= neededPermissions.length) {
            //权限全部已申请到
            if (totalAmount == null || TextUtils.isEmpty(withDrawChannelCode)) {
                XLog.INSTANCE.i(10, "loaning submit bank info error::argument: %s," +
                                "totalAmout: %s"
                        , Boolean.toString(TextUtils.isEmpty(withDrawChannelCode))
                        , Boolean.toString(totalAmount == null));
                XLeoToast.showMessage(R.string.error_occured);
                return;
            }
            if (!idEdittextBankNumberVisivble) {
                applySkypayLoanInfo = new ApplySkypayLoanInfo();
                applySkypayLoanInfo.setLoanAppId(totalAmount.getLoanAppId());
                applySkypayLoanInfo.setWithDrawChannel(withDrawChannelCode);
                applySkypayLoanInfo.setAccountNo("");
                applySkypayLoanInfo.setBankNo("");
                applySkypayLoanInfo.setBankProvince("");
                applySkypayLoanInfo.setBankCity("");
                if (isLawAgreed()) {//已同意贷款
                    submitLoan();
                }
            } else {
                if (isCheckeBankNum()) {
                    applySkypayLoanInfo = new ApplySkypayLoanInfo();
                    applySkypayLoanInfo.setLoanAppId(totalAmount.getLoanAppId());
                    applySkypayLoanInfo.setWithDrawChannel(withDrawChannelCode);
                    applySkypayLoanInfo.setAccountNo(idEdittextBankNumber.getText().toString());
                    applySkypayLoanInfo.setBankNo(bankNo);
                    applySkypayLoanInfo.setBankProvince(bankProvince);
                    applySkypayLoanInfo.setBankCity(bankCity);
                    if (isLawAgreed()) {//已同意贷款
                        submitLoan();
                    }
                }
            }
            return;
        }

        String perm = neededPermissions[permissionIndex];

        if (!Collector.permissionGranted(perm, getContext())) {
            new RxPermissions(getBaseActivity())
                    .requestEach(perm)
                    .subscribe(new Subscriber<Permission>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Permission permission) {
                            if (!permission.granted) {
                                showDialog(permission, permissionIndex);
                            } else {
                                requestPermissions(permissionIndex + 1);
                            }
                        }
                    });

        } else {
            requestPermissions(permissionIndex + 1);
        }
    }

    AlertDialog dialog;

    private void showDialog(Permission permission, int permissionIndex) {
        if (dialog != null) {
            dialog.dismiss();
        }

        dialog = new AlertDialog.Builder(getContext())
                .setTitle("Attention")
                .setCancelable(false)
                .setPositiveButton("OK", (d, which) -> {

                    d.dismiss();
                    if (permission.shouldShowRequestPermissionRationale) {
                        requestPermissions(permissionIndex);

                    } else {
                        TraceManager.INSTANCE.toSettingPermissionActivity(getBaseActivity(), PermissionUtil.neededPermissions[permissionIndex]);
                    }
                })
                .create();

        dialog.setMessage(getBaseActivity().getString(R.string.need_permission_to_loan)
                + "\n\n" + PermissionUtil.getPermisinssionDesc(getBaseActivity(), permissionIndex));


        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    private void submitLoan() {
        FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.BTN_BANK_INFO_SUBMIT, null);
        //提交贷款
        if (applySkypayLoanInfo != null) {
            mPresenter.applySkypayLoan(applySkypayLoanInfo);//并在提交成功后跳转到提交成功页面
//            XLeoToast.showMessage("准备提交贷款");
        }
    }

    private void gotoLawAgreed() {
        //1、请求协议
        Bundle agreeBundle = new Bundle();
        agreeBundle.putCharSequence(KEY_AGREE, PolicyType.LOAN_AGREEMENT.name());
        agreeBundle.putCharSequence(KEY_LOAN_APP_ID, totalAmount.getLoanAppId() + "");
        Intent intent = new Intent(getContext(), PolicyActivity.class);
        intent.putExtras(agreeBundle);
        startActivityForResult(intent, REQUEST_CODE);
        //2、在activity result里面请求活体检测
    }

    private boolean isLawAgreed() {
        if (!CbAgreed.isChecked()) {
            XLeoToast.showMessage(R.string.show_read_agreement);
        }
        return CbAgreed.isChecked();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }

    @Override
    public void submitButtonStateUpdate(boolean active) {

    }
}
